package com.lib.common.manager

import com.allenliu.versionchecklib.callback.OnCancelListener
import com.allenliu.versionchecklib.v2.AllenVersionChecker
import com.allenliu.versionchecklib.v2.builder.DownloadBuilder
import com.allenliu.versionchecklib.v2.builder.UIData
import com.allenliu.versionchecklib.v2.callback.ForceUpdateListener
import com.lib.common.api.ApiService
import com.lib.common.entity.api.resp.CheckVersionResp
import com.lib.common.helper.api.ApiHelper
import com.lib.common.helper.api.ApiResponse
import com.lib.common.repository.common.ComSharePreHelper
import com.lib.common.repository.common.SpKeyInComSp
import com.lib.framework.base.mvvm.BaseViewModelActivity
import com.lib.framework.manager.RunningActivityManager
import com.lib.framework.network.adapter.request.ApiRequestCallback
import com.lib.framework.utils.AppUtil
import com.lib.framework.utils.DateUtil

/**
 * Copyright (C), 2019-2020
 * FileName: UpdateManager
 * Author: Kevin
 * Date: 2020/3/9 15:20
 * Description: 版本升级管理器
 * History:
 * <author> <time> <version> <desc>
 * 作者姓名 修改时间 版本号 描述
 */
object UpdateManager {

    private const val TAG = "UpdateManager"

    /**
     * 版本更新库操作对象
     */
    private var mDownloadBuilder: DownloadBuilder? = null

    /**
     * 检测版本，每天只检测一次
     */
    fun checkVersion(activity: BaseViewModelActivity<*>) {
        val lastCheckVersionTime = ComSharePreHelper.getLong(SpKeyInComSp.SP_KEY_LAST_CHECK_VERSION_TIME, 0L)
        if (DateUtil.isToday(lastCheckVersionTime)) {
            return
        }

        forceCheckVersion(activity, false)
    }

    /**
     * 强制检测版本，每次调用都检测
     */
    fun forceCheckVersion(activity: BaseViewModelActivity<*>, isPompt: Boolean = true) {
        ComSharePreHelper.putLong(SpKeyInComSp.SP_KEY_LAST_CHECK_VERSION_TIME, System.currentTimeMillis())

        if (isPompt) {
            activity.mViewModel.showLoadingDialog()
        }
        ApiHelper.getService(ApiService::class.java)
            ?.checkVersion()
            ?.request(object : ApiRequestCallback<ApiResponse<CheckVersionResp>> {
                override fun onSuccess(data: ApiResponse<CheckVersionResp>?) {
                    if (isPompt) {
                        activity.mViewModel.closeLoadingDialog()
                    }
                    val checkVersionResp = data?.data
                    if (data?.success != true || checkVersionResp == null) {
                        if (isPompt) {
                            activity.mViewModel.prompt(data?.getErrorText() ?: "获取版本信息失败")
                        }
                        return
                    }

                    checkVersion(activity, checkVersionResp, isPompt)
                }

                override fun onFailure(t: Throwable) {
                    if (isPompt) {
                        activity.mViewModel.closeLoadingDialog()
                        activity.mViewModel.prompt("网络异常")
                    }
                }
            })
    }

    /**
     * 根据最新版本信息 检查版本
     */
    private fun checkVersion(activity: BaseViewModelActivity<*>,
                             checkVersionResp: CheckVersionResp, isPompt: Boolean) {
        val currentVersionNum = AppUtil.getVersionName(activity)
        if (comparisonVersionNum(currentVersionNum, checkVersionResp.latestVer) != -1) {
            if (isPompt) {
                activity.mViewModel.prompt("当前版本已经是最新版本！")
            }
            return
        }

        val ret = comparisonVersionNum(currentVersionNum, checkVersionResp.forceVer)
        val force = ret == -1 || ret == 0 // 是否强制更新


        val uiData = UIData.create()
        uiData.title = if (checkVersionResp.promptTitle.isNullOrEmpty()) {
            "更新版本 v${checkVersionResp.latestVer}"
        } else {
            checkVersionResp.promptTitle ?: ""
        }
        uiData.content = checkVersionResp.promptContent ?: ""
        uiData.downloadUrl = checkVersionResp.latestVerLink ?: ""

        showUpdateDialog(activity, uiData, force)
    }

    /**
     * 显示升级对话框
     */
    private fun showUpdateDialog(activity: BaseViewModelActivity<*>,
                                 uiData: UIData, force: Boolean) {

        mDownloadBuilder = AllenVersionChecker
            .getInstance()
            .downloadOnly(uiData)

        if (force) {
            mDownloadBuilder?.forceUpdateListener = ForceUpdateListener {
                RunningActivityManager.finishAllActivity()
            }
        }

        mDownloadBuilder?.isForceRedownload = true // 是否不使用缓存，强制下载apk
//        mDownloadBuilder?.isShowNotification = true // 显示下载通知栏
//        mDownloadBuilder?.isShowDownloadingDialog = true // 显示下载中对话框
//        mDownloadBuilder?.isShowDownloadFailDialog = true // 显示下载失败对话框

        //自定义下载路径
//        mDownloadBuilder?.downloadAPKPath = Environment.getExternalStorageDirectory().toString() + "/ALLEN/AllenVersionPath2/"

        mDownloadBuilder?.onCancelListener = OnCancelListener { }

        mDownloadBuilder?.executeMission(activity)
    }

    /**
     * 比较版本号
     *
     * @return -1：versionNum01 比 versionNum02 小 ；0：相等；1 versionNum01 比 versionNum02 大；-2：错误版本号
     */
    private fun comparisonVersionNum(versionNum01: String?, versionNum02: String?): Int {
        if (versionNum01.isNullOrEmpty() || versionNum02.isNullOrEmpty()) return -2

        val versionNum01IntList = getVersionNumIntList(versionNum01)
        val versionNum02IntList = getVersionNumIntList(versionNum02)
        if (versionNum01IntList == null || versionNum01IntList.size < 3
            || versionNum02IntList == null || versionNum02IntList.size < 3 ) {
            return -2
        }

        val minLen = if (versionNum01IntList.size < versionNum02IntList.size) {
            versionNum01IntList.size
        } else {
            versionNum02IntList.size
        }

        for (i in 0 until minLen) {
            if (versionNum01IntList[i] > versionNum02IntList[i]) return 1

            if (versionNum01IntList[i] < versionNum02IntList[i]) return -1
        }

        // 共有长度的部分 相等，谁的长度长，谁就大
        return when {
            versionNum01IntList.size < versionNum02IntList.size -> -1
            versionNum01IntList.size > versionNum02IntList.size -> 1
            else -> 0
        }
    }

    /**
     * 获取整数版本号列表，1.0.1，返回（1, 0, 1）
     */
    private fun getVersionNumIntList(versionNum: String?): List<Int>? {
        if (versionNum.isNullOrEmpty()) return null

        val strList = versionNum.split(".").toMutableList()
        if (strList.isEmpty()) return null

        if (strList[0].startsWith("v")
            || strList[0].startsWith("V")) {
            strList[0] = strList[0].substring(1)
        }

        val list = mutableListOf<Int>()
        for (i in strList.indices) {
            list.add(0)
            try {
                list[i] = strList[i].toInt()
            } catch (e: Exception) {
                return null
            }
        }

        return list
    }
}